﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DoNet.Extensions.ServiceExtensions
{
    /// <summary>
    /// HttpContext服务
    /// </summary>
    public static class HttpContextSetup
    {
        /// <summary>
        /// HttpContext启动服务
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddHttpContextSetup(this IServiceCollection services)
        {
            if (services != null)
            {
                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.AddHttpContextAccessor();
            }
            else
                throw new ArgumentNullException(nameof(services));
        }
        /// <summary>
        /// 
        /// </summary>
        private static IHttpContextAccessor? httpContextAccessor;
        /// <summary>
        /// 
        /// </summary>
        public static HttpContext? HttpContext => httpContextAccessor?.HttpContext;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStaticHttpContextAccessor(this IApplicationBuilder app)
        {
            httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            return app;
        }

        /// <summary>
        /// 获取客户Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                var remoteIpAddress = context.Connection.RemoteIpAddress;
                if (remoteIpAddress != null)
                {
                    return remoteIpAddress.ToString();
                }
            }
            else
            {
                return ip;
            }
            return string.Empty;
        }
    }
}
